﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Application.Services;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Linq;
using YaAppoint.Response;

namespace YaAppoint.Rules
{
    public class RuleTemplateAppService(IRepository<RuleTemplate,Guid> ruleTemplateRepository,
                                        AsyncQueryableExecuter queryableExecuter,
                                        IMapper mapper): ApplicationService, IRuleTemplateAppService, ITransientDependency
    {
        private readonly IRepository<RuleTemplate, Guid> _ruleTemplateRepository = ruleTemplateRepository;
        private readonly AsyncQueryableExecuter _queryableExecuter= queryableExecuter;
        private readonly IMapper _mapper = mapper;

        /// <summary>
        /// 新建目录
        /// </summary>
        public async Task<BackJson> CreateDirectory(RuleTemplateCreateDto dto)
        {
            RuleTemplate directory = _mapper.Map<RuleTemplateCreateDto, RuleTemplate>(dto);
            await _ruleTemplateRepository.InsertAsync(directory);
            return new BackJson
            {
                code = 0,
                msg = "目录创建成功",
                data= new { 
                    id= directory.Id,
                    label= directory.Name,
                    isDirectory = true
                }
            };
        }


        /// <summary>
        /// 新建模板
        /// </summary>
        public async Task<BackJson> CreateTemplate(RuleTemplateCreateDto dto)
        {
            RuleTemplate template = _mapper.Map<RuleTemplateCreateDto, RuleTemplate>(dto);
            await _ruleTemplateRepository.InsertAsync(template);
            return new BackJson
            {
                code = 0,
                msg = "规则模板创建成功",
                data = new
                {
                    id = template.Id,
                    label = template.Name,
                    isDirectory = false
                }
            };
        }


        /// <summary>
        /// 删除目录
        /// </summary>
        public async Task<BackJson> DeleteDirectory(Guid id)
        {
            var directory = await _ruleTemplateRepository.FirstOrDefaultAsync(r => r.Id == id);
            if (directory != null)
            {
                if (directory.Children !=null && directory.Children.Count>0)
                {
                    List<Guid> idsForDelete = new List<Guid>();
                    foreach (var child in directory.Children)
                    {
                        // 递归删除
                        await DeleteRecursive(child);
                    }
                }
                await _ruleTemplateRepository.DeleteAsync(id);
            }
            return new BackJson
            {
                code = 0,
                msg = "目录删除成功"
            };
        }

        public async Task DeleteRecursive(RuleTemplate ruleTemplate)
        {
            if (ruleTemplate.Children != null && ruleTemplate.Children.Count > 0)
            {
                foreach (var child in ruleTemplate.Children)
                {
                    if (child.Children != null && child.Children.Count > 0)
                    {
                        await DeleteRecursive(child);
                    }
                }
            }
            await _ruleTemplateRepository.DeleteAsync(ruleTemplate);
        }

        /// <summary>
        /// 删除模板
        /// </summary>
        public async Task<BackJson> DeleteTemplate(Guid id)
        {
            var template = await _ruleTemplateRepository.FirstOrDefaultAsync(t => t.Id == id);
            if (template != null)
            { 
                await _ruleTemplateRepository.DeleteAsync(id);
            }
            return new BackJson
            {
                code = 0,
                msg = "删除成功"
            };
        }


        /// <summary>
        /// 目录编辑提交
        /// </summary>
        public async Task<BackJson> EditDirectory(RuleTemplateDto dto)
        {
            var directory = await _ruleTemplateRepository.FirstOrDefaultAsync(d => d.Id == dto.Id);
            if (directory == null)
            {
                throw new BusinessException(CustomErrorCodes.TemplateDirectoryNotExist);
            }
            _mapper.Map<RuleTemplateDto, RuleTemplate>(dto, directory);
            await _ruleTemplateRepository.UpdateAsync(directory);
            return new BackJson
            {
                code = 0,
                msg = "保存成功",
                data = new 
                {
                    id=dto.Id,
                    label=dto.Name,
                    parentId =dto.ParentId
                }
            };
        }

        /// <summary>
        /// 模板编辑提交
        /// </summary>
        public async Task<BackJson> EditTemplate(RuleTemplateDto dto)
        {
            var tempalte = await _ruleTemplateRepository.FirstOrDefaultAsync(t => t.Id == dto.Id);
            if (tempalte == null)
            {
                throw new BusinessException(CustomErrorCodes.RuleTemplateNotExist);
            }
            _mapper.Map<RuleTemplateDto, RuleTemplate>(dto, tempalte);
            await _ruleTemplateRepository.UpdateAsync(tempalte);
            return new BackJson
            {
                code = 0,
                msg = "保存成功",
                data = new
                {
                    id = tempalte.Id,
                    label = tempalte.Name,
                    isDirectory = false
                }
            };
        }

        /// <summary>
        /// 加载树形数据
        /// </summary>
        public async Task<BackJson> GetTreeDate(string? filerName)
        {
            var query = await _ruleTemplateRepository.GetQueryableAsync();
            query = query.Where(r => r.ParentId == null);
            if (!string.IsNullOrEmpty(filerName))
            {
                query = query.Where(r => r.Name.Contains(filerName));
            }
            query = query.OrderBy(r => r.IsDirectory ? 0 : 1).ThenByDescending(r => r.Order);
            var topLevelList = await _queryableExecuter.ToListAsync(query);

            var data = new List<TreeNode>();
            foreach (var item in topLevelList)
            {
                var node = GetNodeRecursiveAsync(item);
                data.Add(node);
            }
            return new BackJson
            {
                code=0,
                data = data
            };
        }

        public TreeNode GetNodeRecursiveAsync(RuleTemplate template)
        {
            var res = MapToTreeNode(template);
            if (template.Children != null || template.Children!.Count > 0)
            {
                var children = template.Children.OrderBy(r => r.IsDirectory ? 0 : 1).ThenByDescending(r => r.Order).ToList();
                foreach (var child in children)
                {
                    res.Children!.Add(MapToTreeNode(child));
                }
            }
            return res;
        }

        private TreeNode MapToTreeNode(RuleTemplate template)
        { 
            var node = new TreeNode();
            node.Id = template.Id;
            node.Label = template.Name;
            node.IsDirectory = template.IsDirectory;
            if (template.Children == null || template.Children.Count == 0)
            {
                node.Children = null;
            }
            else
            {
                node.Children = new List<TreeNode>();
            }
            return node;
        }

        /// <summary>
        /// 加载详情
        /// </summary>
        public async Task<BackJson> LoadDetail(Guid id)
        {
            var template = await _ruleTemplateRepository.FirstOrDefaultAsync(t=>t.Id==id);
            if (template == null)
            {
                throw new BusinessException(CustomErrorCodes.NodeNotExist);
            }

            return new BackJson
            {
                code = 0,
                data = _mapper.Map<RuleTemplate, RuleTemplateDto>(template)
            };
        }

    }


    /// <summary>
    /// 适配 ElementUI Tree组件数据的节点类型
    /// </summary>
    [Serializable]
    public class TreeNode
    { 
        public Guid Id { get; set; }

        public string Label { get; set; }

        public List<TreeNode>? Children { get; set; }

        public bool IsDirectory { get; set; } = false;
    }
}
